package cn.tedu.aiumall.product.webapi.service.impl;

import cn.tedu.aiumall.common.exception.AiuMallServiceException;
import cn.tedu.aiumall.common.pojo.product.dto.PictureAddNewDTO;
import cn.tedu.aiumall.common.pojo.product.dto.ReturnSpuDetail;
import cn.tedu.aiumall.common.pojo.product.dto.SpuAddNewDTO;
import cn.tedu.aiumall.common.pojo.product.entity.Spu;
import cn.tedu.aiumall.common.pojo.product.entity.SpuDetail;
import cn.tedu.aiumall.common.pojo.product.vo.AlbumStandardVO;
import cn.tedu.aiumall.common.pojo.product.vo.BrandStandardVO;
import cn.tedu.aiumall.common.pojo.product.vo.CategoryStandardVO;
import cn.tedu.aiumall.common.pojo.product.vo.SpuListItemVO;
import cn.tedu.aiumall.common.restful.ResponseCode;
import cn.tedu.aiumall.product.service.IPictureService;
import cn.tedu.aiumall.product.service.ISpuService;
import cn.tedu.aiumall.product.webapi.mapper.*;
import cn.tedu.aiumall.product.webapi.util.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理Spu业务的实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class SpuServiceImpl implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private IPictureService pictureService;

    public SpuServiceImpl() {
        log.info("创建业务对象：SpuServiceImpl");
    }

    @Override
    public ReturnSpuDetail addNew(SpuAddNewDTO spuAddNewDTO) {
        // 从参数spuAddNewDTO中取出brandId
        Long brandId = spuAddNewDTO.getBrandId();
        // 调用brandMapper的getDetailsById()方法查询品牌
        BrandStandardVO brand = brandMapper.getStandardById(brandId);
        // 判断查询结果是否为null
        if (brand == null) {
            // 是：抛出异常：选择的品牌不存在
            String message = "新增Spu失败，尝试绑定的品牌数据不存在！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.NOT_FOUND, message);
        }

        // 判断查询到的品牌的enable是否为0
        if (brand.getEnable() == 0) {
            // 是：抛出异常
            String message = "新增Spu失败，尝试绑定的品牌已经被禁用！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.CONFLICT, message);
        }

        // 从参数spuAddNewDTO中取出categoryId
        Long categoryId = spuAddNewDTO.getCategoryId();
        // 调用categoryMapper的getDetailsById()方法查询类别
        CategoryStandardVO category = categoryMapper.getStandardById(categoryId);
        // 判断查询结果是否为null
        if (category == null) {
            // 是：抛出异常：选择的类别不存在
            String message = "新增Spu失败，尝试绑定的类别数据不存在！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.NOT_FOUND, message);
        }

        // 判断查询到的类别的enable是否为0
        if (category.getEnable() == 0) {
            // 是：抛出异常
            String message = "新增Spu失败，尝试绑定的类别已经被禁用！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.CONFLICT, message);
        }

        // 判断查询到的类别的isParent是否为1
        if (category.getIsParent() == 1) {
            // 是：抛出异常
            String message = "新增Spu失败，尝试绑定的类别包含子级类别，不允许使用此类别！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.CONFLICT, message);
        }

        // 从参数spuAddNewDTO中取出albumId
        Long albumId = spuAddNewDTO.getAlbumId();
        // 调用albumMapper的getDetailsById()方法查询相册
        AlbumStandardVO album = albumMapper.getStandardById(albumId);
        // 判断查询结果是否为null
        if (album == null) {
            // 是：抛出异常：选择的相册不存在
            String message = "新增Spu失败，尝试绑定的相册数据不存在！";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.NOT_FOUND, message);
        }

        // 获取id（由别处生成）
        Long id = IdUtils.getId();

        // 创建Spu对象
        Spu spu = new Spu();
        String[] pics= spuAddNewDTO.getPictures();
        if (pics.length==0){
            throw new AiuMallServiceException(ResponseCode.CONFLICT,"请上传图片");
        }
        StringBuilder pictures=new StringBuilder();
        for (String pic:pics){
            pictures.append(pic);
        }
        log.info("pictures:{}",pictures);
        String substring = pictures.substring(2, pictures.length() - 2);
        log.info("sbutring:{}",substring);
        String[] split = substring.split("\"\"");
        StringBuilder stringBuilder=new StringBuilder();
        for (int i=0;i<split.length;i++){
            if (i!=split.length-1){
                stringBuilder.append(split[i]+",");
            }else {
                stringBuilder.append(split[i]);
            }
        }
        log.info("stringBuffer:{}",stringBuilder);
        // 将参数spuAddNewDTO的属性值复制到Spu对象中
        BeanUtils.copyProperties(spuAddNewDTO, spu);
        spu.setPictures(stringBuilder.toString());
        // 补全Spu对象的属性值：id >>> 自行决定
        spu.setId(id);
        // 补全Spu对象的属性值：brandName >>> 前序查询品牌的结果中取出
        spu.setBrandName(brand.getName());
        // 补全Spu对象的属性值：categoryName >>> 前序查询类别的结果中取出
        spu.setCategoryName(category.getName());
        // 补全Spu对象的属性值：sales / commentCount / positiveCommentCount >>> 0
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);
        // 补全Spu对象的属性值：isDelete / isPublished >>> 0
        spu.setIsDeleted(0);
        spu.setIsPublished(0);
        // 补全Spu对象的属性值：isNewArrival / isRecommend >>> 自行决定
        spu.setIsNewArrival(0);
        spu.setIsRecommend(0);
        // 补全Spu对象的属性值：isChecked >>> 0
        spu.setIsChecked(0);
        // 补全Spu对象的属性值：checkUser / gmtCheck >>> null
        // 调用spuMapper的int insert(Spu spu)方法插入Spu数据，并获取返回值
        int rows = spuMapper.insert(spu);
        // 判断返回值是否不为1
        if (rows != 1) {
            // 是：抛出异常
            String message = "新增Spu失败！服务器忙，请稍后再次尝试！[错误代码：1]";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.ERR_INSERT, message);
        }

        PictureAddNewDTO pictureAddNewDTO=new PictureAddNewDTO();
        pictureAddNewDTO.setAlbumId(spuAddNewDTO.getAlbumId());
        pictureAddNewDTO.setDescription(spuAddNewDTO.getDescription());
        pictureAddNewDTO.setUrl(split);
        pictureService.addNew(pictureAddNewDTO);

        // 创建SpuDetail对象
        SpuDetail spuDetail = new SpuDetail();
        // 补全SpuDetail对象的属性值：spuId >>> 同以上Spu对象的id
        spuDetail.setSpuId(id);
        // 补全SpuDetail对象的属性值：detail >>> 来自spuAddNewDTO参数
        spuDetail.setDetail(spuAddNewDTO.getDetail());
        // 调用spuDetailMapper的int insert(SpuDetail spuDetail)方法插入SpuDetail数据，并获取返回值
        rows = spuDetailMapper.insert(spuDetail);
        // 判断返回值是否不为1
        if (rows != 1) {
            // 是：抛出异常
            String message = "新增Spu失败！服务器忙，请稍后再次尝试！[错误代码：2]";
            log.warn(message);
            throw new AiuMallServiceException(ResponseCode.ERR_INSERT, message);
        }
        ReturnSpuDetail returnSpuDetail=new ReturnSpuDetail();
        returnSpuDetail.setSpuId(id);
        returnSpuDetail.setAlbumId(albumId);
        returnSpuDetail.setAttributeTemplateId(spuAddNewDTO.getAttributeTemplateId());

        return returnSpuDetail;
    }

    @Override
    public void deleteById(Long id) {
        log.info("开始处理【删除SPU】的业务，参数：{}", id);
        // 检查尝试删除的SPU是否存在
        Object queryResult = spuMapper.getStandardById(id);
        if (queryResult == null) {
            throw new AiuMallServiceException(ResponseCode.NOT_FOUND, "删除SPU失败，尝试访问的数据不存在！");
        }

        // 执行删除
        log.info("即使删除id为{}的SPU……", id);
        int rows = spuMapper.deleteById(id);
        if (rows != 1) {
            throw new AiuMallServiceException(ResponseCode.ERR_DELETE, "删除SPU失败，服务器忙，请稍后再次尝试！");
        }
        log.info("删除完成！");
    }

    @Override
    public List<SpuListItemVO> list() {
        log.info("开始处理查询所有spu信息");
        List<SpuListItemVO> list = spuMapper.list();
        return list;
    }

}
